package com.ikun.kunpicturebackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ikun.kunpicturebackend.domain.Space;
import com.ikun.kunpicturebackend.domain.SpaceUser;
import com.ikun.kunpicturebackend.domain.User;
import com.ikun.kunpicturebackend.exception.BusinessException;
import com.ikun.kunpicturebackend.exception.ErrorCode;
import com.ikun.kunpicturebackend.exception.ThrowUtils;
import com.ikun.kunpicturebackend.model.dto.space.SpaceAddRequest;
import com.ikun.kunpicturebackend.model.dto.space.SpaceQueryRequest;
import com.ikun.kunpicturebackend.model.enums.SpaceLevelEnum;
import com.ikun.kunpicturebackend.model.enums.SpaceRoleEnum;
import com.ikun.kunpicturebackend.model.enums.SpaceTypeEnum;
import com.ikun.kunpicturebackend.model.vo.SpaceVO;
import com.ikun.kunpicturebackend.model.vo.UserVO;
import com.ikun.kunpicturebackend.service.SpaceService;
import com.ikun.kunpicturebackend.mapper.SpaceMapper;
import com.ikun.kunpicturebackend.service.SpaceUserService;
import com.ikun.kunpicturebackend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author 32144
 * @description 针对表【space(空间)】的数据库操作Service实现
 * @createDate 2025-10-07 16:49:38
 */
@Service
public class SpaceServiceImpl extends ServiceImpl<SpaceMapper, Space>
        implements SpaceService {

    @Resource
    private TransactionTemplate transactionTemplate;

    @Resource
    private UserService userService;

    private final Map<Long, Object> lockMap = new ConcurrentHashMap<>();

    @Resource
    private SpaceUserService spaceUserService;

    @Override
    public void validSpace(Space space, boolean create) {
        ThrowUtils.throwIf(space == null, ErrorCode.PARAMS_ERROR);
        String spaceName = space.getSpaceName();
        Integer spaceLevel = space.getSpaceLevel();
        SpaceLevelEnum levelEnum = SpaceLevelEnum.getEnumByValue(spaceLevel);
        // 空间类型
        Integer spaceType = space.getSpaceType();
        SpaceTypeEnum typeEnum = SpaceTypeEnum.getEnumByValue(spaceType);

        if (create) {
            // 空间名和级别不能为空
            ThrowUtils.throwIf(StrUtil.isBlank(spaceName), ErrorCode.PARAMS_ERROR, "空间名不能为空");
            ThrowUtils.throwIf(spaceLevel == null, ErrorCode.PARAMS_ERROR, "空间级别不能为空");
            // 空间类型不能为空
            ThrowUtils.throwIf(spaceType == null, ErrorCode.PARAMS_ERROR, "空间类型不能为空");
        }

        // 修改数据时，如果要改空间级别
        if (spaceLevel != null && levelEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间级别不存在");
        }
        if (spaceType != null && typeEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间类型不存在");
        }
        if (StrUtil.isNotBlank(spaceName) && spaceName.length() > 30) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间名称过长");
        }
    }

    @Override
    public void fillSpaceBySpaceLevel(Space space) {
        // 根据空间级别，自动填充限额
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(space.getSpaceLevel());
        if (spaceLevelEnum != null) {
            long maxSize = spaceLevelEnum.getMaxSize();
            if (space.getMaxSize() == null) {
                space.setMaxSize(maxSize);
            }
            long maxCount = spaceLevelEnum.getMaxCount();
            if (space.getMaxCount() == null) {
                space.setMaxCount(maxCount);
            }
        }
    }

    @Override
    public Long addSpace(SpaceAddRequest addRequest, User loginUser) {
        // 请求转实体类space
        Space space = new Space();
        BeanUtil.copyProperties(addRequest, space);
        // 如果空间名为空则设置为“爱坤空间”
        if (StrUtil.isBlank(space.getSpaceName())) {
            space.setSpaceName("爱坤空间");
        }
        // 如果级别为空则设置为普通级别
        if (space.getSpaceLevel() == null) {
            space.setSpaceLevel(SpaceLevelEnum.COMMON.getValue());
        }
        // 如果空间类型为空，设置为私人空间
        if (space.getSpaceType() == null) {
            space.setSpaceLevel(SpaceTypeEnum.PRIVATE.getValue());
        }
        // 填充数据fillSpaceBySpaceLevel
        fillSpaceBySpaceLevel(space);
        // 校验
        validSpace(space, true);
        // 权限校验：普通用户不能创建指定级别的空间
        Long userId = loginUser.getId();
        space.setUserId(userId);
        if (space.getSpaceLevel() != SpaceLevelEnum.COMMON.getValue() && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限创建指定级别的空间");
        }

        Object lock = lockMap.computeIfAbsent(userId, key -> new Object());
        synchronized (lock) {
            try {
                Long newSpaceId = transactionTemplate.execute(status -> {
                    //查询空间判断是否唯一
                    boolean exists = this.lambdaQuery()
                            .eq(Space::getUserId, userId)
                            .eq(Space::getSpaceType, space.getSpaceType())
                            .exists();
                    ThrowUtils.throwIf(exists, ErrorCode.OPERATION_ERROR, "每类空间用户只能创建一个");
                    // 保存空间信息到数据库
                    boolean result = this.save(space);
                    ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
                    // 如果是创建团队空间，将创建人添加到空间成员表中
                    if (space.getSpaceType().equals(SpaceTypeEnum.TEAM.getValue())) {
                        SpaceUser spaceUser = new SpaceUser();
                        spaceUser.setUserId(userId);
                        spaceUser.setSpaceId(space.getId());
                        // 创建人为团队空间的管理员
                        spaceUser.setSpaceRole(SpaceRoleEnum.ADMIN.getValue());
                        boolean save = spaceUserService.save(spaceUser);
                        ThrowUtils.throwIf(!save, ErrorCode.OPERATION_ERROR);
                    }
                    // 返回空间id
                    return space.getId();
                });
                return Optional.ofNullable(newSpaceId).orElse(-1L);
            } finally {
                lockMap.remove(userId);
            }
        }
    }

    @Override
    public void checkSpaceAuth(User loginUser, Space space) {
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);
        ThrowUtils.throwIf(space == null, ErrorCode.PARAMS_ERROR);
        // 本人/管理员
        ThrowUtils.throwIf(!space.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser), ErrorCode.NO_AUTH_ERROR);
    }

    @Override
    public SpaceVO getSpaceVO(Space space, HttpServletRequest request) {
        SpaceVO spaceVO = SpaceVO.objToVo(space);
        Long userId = space.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
            spaceVO.setUser(userVO);
        }
        return spaceVO;
    }

    @Override
    public QueryWrapper<Space> getQueryWrapper(SpaceQueryRequest spaceQueryRequest) {
        QueryWrapper<Space> queryWrapper = new QueryWrapper<>();
        if (spaceQueryRequest == null) {
            return queryWrapper;
        }
        Long id = spaceQueryRequest.getId();
        Long userId = spaceQueryRequest.getUserId();
        String spaceName = spaceQueryRequest.getSpaceName();
        Integer spaceLevel = spaceQueryRequest.getSpaceLevel();
        Integer spaceType = spaceQueryRequest.getSpaceType();
        String sortField = spaceQueryRequest.getSortField();
        String sortOrder = spaceQueryRequest.getSortOrder();
        // 拼接查询条件
        queryWrapper.eq(id != null, "id", id)
                .eq(userId != null, "userId", userId)
                .eq(spaceLevel != null, "spaceLevel", spaceLevel)
                .eq(spaceType != null, "spaceType", spaceType)
                .like(StrUtil.isNotBlank(spaceName), "spaceName", spaceName)
                .orderBy(StrUtil.isNotBlank(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    @Override
    public Page<SpaceVO> getSpaceVOPage(Page<Space> spacePage, HttpServletRequest request) {
        // 获取空间列表
        List<Space> spaceList = spacePage.getRecords();
        // 待返回结果
        Page<SpaceVO> spaceVOPage = new Page<>(spacePage.getCurrent(), spacePage.getSize(), spacePage.getTotal());
        // 空间列表为空，直接返回
        if (CollUtil.isEmpty(spaceList)) {
            return spaceVOPage;
        }

        // 转换为SpaceVO集合
        List<SpaceVO> spaceVOList = spaceList.stream()
                .map(SpaceVO::objToVo)
                .collect(Collectors.toList());

        // 获取创建用户id集合
        Set<Long> userIdSet = spaceList.stream().map(Space::getUserId).collect(Collectors.toSet());
        // 查询用户信息(用户id -> 用户信息)
        Map<Long, List<User>> userMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));

        // 开始关联用户信息
        spaceVOList.forEach(spaceVO -> {
            Long userId = spaceVO.getUserId();
            User user = userMap.get(userId).get(0);
            spaceVO.setUser(BeanUtil.copyProperties(user, UserVO.class));
        });
        spaceVOPage.setRecords(spaceVOList);
        return spaceVOPage;
    }
}




